package cn.com.chec.en.util.images;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import javax.imageio.ImageIO;

public class ImageMarkLogoByText {
	public static void markByText(String logoText, String srcImgPath,
			String targerPath) {
		markByText(logoText, srcImgPath, targerPath, null);
	}

	public static void markByText(String logoText, String srcImgPath,
			String targerPath, Integer degree) {
		InputStream is = null;
		OutputStream os = null;
		try {
			Image srcImg = ImageIO.read(new File(srcImgPath));
			BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null),
					srcImg.getHeight(null), 1);

			Graphics2D g = buffImg.createGraphics();
			g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
					RenderingHints.VALUE_INTERPOLATION_BILINEAR);

			g.drawImage(
					srcImg.getScaledInstance(srcImg.getWidth(null),
							srcImg.getHeight(null), 4), 0, 0, null);
			if (degree != null) {
				g.rotate(Math.toRadians(degree.intValue()),
						buffImg.getWidth() / 2.0D, buffImg.getHeight() / 2.0D);
			}

			g.setColor(Color.gray);

			g.setFont(new Font("宋体", 1, 30));
			float alpha = 0.5F;
			g.setComposite(AlphaComposite.getInstance(10, alpha));

			g.drawString(logoText, srcImg.getWidth(null) / 2,
					srcImg.getHeight(null) - 100);
			g.dispose();
			os = new FileOutputStream(targerPath);

			ImageIO.write(buffImg, "JPG", os);
		} catch (Exception e) {
			e.printStackTrace();
			try {
				if (is != null)
					is.close();
			} catch (Exception ex) {
				ex.printStackTrace();
			}
			try {
				if (os != null)
					os.close();
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		} finally {
			try {
				if (is != null)
					is.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			try {
				if (os != null)
					os.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) {
		String srcImgPath = "E:/ent/照片/王琪/温家宝.jpg";
		String logoText = "CHINA HUADIAN\r\nENGINEERING CO.LTD";
		String targerPath = "E:/ent/照片/王琪/1_text.jpg";
		String targerPath2 = "E:/ent/照片/王琪/1_text2.jpg";

		markByText(logoText, srcImgPath, targerPath);

		markByText(logoText, srcImgPath, targerPath2, Integer.valueOf(-45));
	}
}